package com.joint.web.action.com;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.*;
import com.joint.base.service.activiti.WorkflowService;
import com.joint.base.util.DataUtil;
import com.joint.base.util.EntityUtil;
import com.joint.core.entity.manage.Dispatch;
import com.joint.core.entity.manage.DispatchRevise;
import com.joint.core.service.DispatchReviseService;
import com.joint.core.service.DispatchService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;


@ParentPackage("com")
public class AjaxStepbriefAction extends BaseFlowAction {

    @Resource
    private ProcessBriefService processBriefService;
    @Resource
    private StepBriefService stepBriefService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private RoleService roleService;
    @Resource
    private PowerService powerService;
    @Resource
    private PostService postService;
    @Resource
    private CommonConfigService commonConfigService;
    /**
     * 流程简要表(读)
     */
    private ProcessBrief processBrief;
    /**
     * 步骤简要表(读)
     */
    private StepBrief stepBrief;

    private String commonConfigId;
    private int stepNo;
    private int backStepNo;
    private String stepName;
    private List<String> actionType;
    private String jointlySing;
    private int routeType;
    private int nextStepNo;
    private String roleId;
    private String departId;
    private String postId;
    private String powerId;
    private String variableName;
    private List<String> specialType;
    private Set<String> fieldNames;
    private String allmans;

    /**
     * 项目视图
     * @return
     */
    public String execute(){
        return "stepbrief";
    }



    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("stepNo");
        pager.setOrderType(BaseEnum.OrderType.asc);
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();
        Map<String,Object> params = new HashMap<String,Object>();
        //内嵌视图这里要加上
        if (StringUtils.isNotEmpty(parentId)){
            processBrief = processBriefService.get(parentId);
            params.put("processBrief",processBrief);
        }
        params.put("company", com);
        params.put("state", BaseEnum.StateEnum.Enable);

        pager = stepBriefService.findByPager(pager, params);

        List<StepBrief>  stepBriefList;
        if (pager.getTotalCount() > 0){
            stepBriefList = (List<StepBrief>) pager.getList();
        }else{
            stepBriefList = new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(StepBrief stepBrief: stepBriefList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",stepBrief.getId());
            rMap.put("stepNo", stepBrief.getStepNo());
            rMap.put("name", stepBrief.getName());
            rMap.put("creater", stepBrief.getCreater() != null ? stepBrief.getCreater().getName() : "");
            rMap.put("createDate", DataUtil.DateToString(stepBrief.getCreateDate(), "yyyy-MM-dd"));
            rMap.put("routeType", stepBrief.getRouteType()==2?"条件路由":"一般路由");
            if(stepBrief.getRouteType()==2){
                String nextStepNo = "";
                List<StepCon> stepConList = stepBrief.getStepConList();
                if(stepConList != null){
                    for(StepCon stepCon:stepConList){
                        if(stepCon.getStepBrief() != null && stepCon.getState().name().equals("Enable")){
                            nextStepNo += stepCon.getStepNo()+",";
                        }
                    }
                }
                if(StringUtils.isNotEmpty(nextStepNo)){
                    nextStepNo = nextStepNo.substring(0, nextStepNo.length()-1);
                }
                rMap.put("nextStepNo",nextStepNo);
            }else{
                rMap.put("nextStepNo",stepBrief.getNextStepNo());
            }
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }
        data.put("dataRows", dataRows);
        data.put("page", page);
        data.put("rows", rows);
        long recordsNum = pager.getTotalCount();
        data.put("total", calcPageNum(recordsNum));
        data.put("records", recordsNum);
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String input(){
        if (StringUtils.isNotEmpty(parentId)){
            processBrief = processBriefService.get(parentId);
            stepBrief = new StepBrief();
            stepBrief.setProcessBrief(processBrief);
        }
        if (StringUtils.isNotEmpty(keyId)){
            stepBrief = stepBriefService.get(keyId);
        }
        try {
            Class table =  Class.forName(stepBrief.getProcessBrief().getTableKey());
            fieldNames = Sets.newHashSet();
            String[] allField =  EntityUtil.getFiledName(table);
            for(String field:allField){
                if(field.startsWith("duty") == true){
                    fieldNames.add(field);
                }
            }
            // LogUtil.info("fieldNames:"+ fieldNames);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return "input";
    }

    /**
     * 步骤简要表保存
     * @return
     */
    public String save(){

        if(StringUtils.isNotEmpty(keyId)){
            stepBrief = stepBriefService.get(keyId);
        }else{
            stepBrief = new StepBrief();
            stepBrief.setCreater(usersService.getLoginInfo());
        }
        if(StringUtils.isNotEmpty(parentId)){
            processBrief = processBriefService.get(parentId);
            stepBrief.setProcessBrief(processBrief);
        }
        CommonConfig commonConfig = null;
        if(StringUtils.isNotEmpty(commonConfigId)){
            commonConfig = commonConfigService.get(commonConfigId);
        }else{
            commonConfig = new CommonConfig();
        }
        if(StringUtils.equals(allmans, "1")){
            commonConfig.setAllmans(true);
        }else{
            commonConfig.setAllmans(false);
        }
        commonConfig.setDepartmentSet(getDepartSpit(departId));
        commonConfig.setRoleSet(getRoleSpit(roleId));
        commonConfig.setPowerSet(getPowerSpit(powerId));
        commonConfig.setPostSet(getPostSpit(postId));
        commonConfig.setVariable(variableName);
        commonConfigService.updateAndEnable(commonConfig);
        stepBrief.setCommonConfig(commonConfig);
        stepBrief.setName(stepName);
        stepBrief.setStepNo(stepNo);
        stepBrief.setBackStepNo(backStepNo);
        String strActionType = "";
        if(actionType != null && actionType.size()>0){
            for(String type:actionType){
                strActionType += type;
            }
        }
        stepBrief.setActionType(strActionType);
        if(StringUtils.equals(jointlySing, "1")){
            stepBrief.setJointlySing(true);
        }else{
            stepBrief.setJointlySing(false);
        }
        stepBrief.setRouteType(routeType);
        stepBrief.setNextStepNo(nextStepNo);
        String strSpecialType = "";
        if(specialType !=null && specialType.size()>0){
            for(String type:specialType){
                strSpecialType += type;
            }
        }

        stepBrief.setSpecialType(strSpecialType);
        stepBrief.setCompany(usersService.getCompanyByUser());
        if(StringUtils.isNotEmpty(keyId)){
            stepBriefService.update(stepBrief);
        }else{
            stepBriefService.save(stepBrief);
        }
        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }


    /**
     * 分割字符串
     *
     * @param str
     * @return
     */
    private Set<Users> getUserSpit(String str) {
        Set<Users> usersSet = new HashSet<Users>();
        String[] ary = str.split(",");
        for (String item : ary) {
            if (com.joint.base.util.StringUtils.isNotEmpty(item)) {
                usersSet.add(usersService.get(item));
            }

        }
        return usersSet;
    }

    private Set<Department> getDepartSpit(String str) {
        Set<Department> departSet = new HashSet<Department>();
        if(com.joint.base.util.StringUtils.isEmpty(str)) return departSet;
        String[] ary = str.split(",");
        for (String item : ary) {
            if (com.joint.base.util.StringUtils.isNotEmpty(item)) {
                departSet.add(departmentService.get(item));
            }
        }
        return departSet;
    }

    private Set<Post> getPostSpit(String str) {
        Set<Post> postSet = new HashSet<Post>();
        if(com.joint.base.util.StringUtils.isEmpty(str)) return postSet;
        String[] ary = str.split(",");
        for (String item : ary) {
            if (com.joint.base.util.StringUtils.isNotEmpty(item)) {
                postSet.add(postService.get(item));
            }
        }
        return postSet;
    }

    private Set<Role> getRoleSpit(String str) {
        Set<Role> roleSet = Sets.newHashSet();
        if(com.joint.base.util.StringUtils.isEmpty(str)) return roleSet;
        String[] ary = str.split(",");
        for (String item : ary) {
            if (com.joint.base.util.StringUtils.isNotEmpty(item)) {
                roleSet.add(roleService.get(item));
            }
        }
        return roleSet;
    }

    private Set<Power> getPowerSpit(String str) {
        Set<Power> powerSet = Sets.newHashSet();
        if(com.joint.base.util.StringUtils.isEmpty(str)) return powerSet;
        String[] ary = str.split(",");
        for (String item : ary) {
            if (com.joint.base.util.StringUtils.isNotEmpty(item)) {
                powerSet.add(powerService.get(item));
            }
        }
        return powerSet;
    }

    //删除
    public String delete(){
        if(StringUtils.isNotEmpty(keyId)){
            stepBrief = stepBriefService.get(keyId);
            stepBrief.setState(BaseEnum.StateEnum.Delete);
            stepBriefService.update(stepBrief);
        }
        return  ajaxHtmlCallback("200", "删除成功！","操作状态");
    }

    public StepBrief getStepBrief() {
        return stepBrief;
    }

    public void setStepBrief(StepBrief stepBrief) {
        this.stepBrief = stepBrief;
    }

    public ProcessBrief getProcessBrief() {
        return processBrief;
    }

    public void setProcessBrief(ProcessBrief processBrief) {
        this.processBrief = processBrief;
    }

    public String getCommonConfigId() {
        return commonConfigId;
    }

    public void setCommonConfigId(String commonConfigId) {
        this.commonConfigId = commonConfigId;
    }

    public int getNextStepNo() {
        return nextStepNo;
    }

    public void setNextStepNo(int nextStepNo) {
        this.nextStepNo = nextStepNo;
    }

    public int getStepNo() {
        return stepNo;
    }

    public void setStepNo(int stepNo) {
        this.stepNo = stepNo;
    }

    public String getStepName() {
        return stepName;
    }

    public void setStepName(String stepName) {
        this.stepName = stepName;
    }

    public List<String> getActionType() {
        return actionType;
    }

    public void setActionType(List<String> actionType) {
        this.actionType = actionType;
    }

    public String getJointlySing() {
        return jointlySing;
    }

    public void setJointlySing(String jointlySing) {
        this.jointlySing = jointlySing;
    }

    public int getRouteType() {
        return routeType;
    }

    public void setRouteType(int routeType) {
        this.routeType = routeType;
    }

    public String getRoleId() {
        return roleId;
    }

    public void setRoleId(String roleId) {
        this.roleId = roleId;
    }

    public String getDepartId() {
        return departId;
    }

    public void setDepartId(String departId) {
        this.departId = departId;
    }

    public String getPostId() {
        return postId;
    }

    public void setPostId(String postId) {
        this.postId = postId;
    }

    public String getPowerId() {
        return powerId;
    }

    public void setPowerId(String powerId) {
        this.powerId = powerId;
    }

    public String getVariableName() {
        return variableName;
    }

    public void setVariableName(String variableName) {
        this.variableName = variableName;
    }

    public List<String> getSpecialType() {
        return specialType;
    }

    public void setSpecialType(List<String> specialType) {
        this.specialType = specialType;
    }

    public Set<String> getFieldNames() {
        return fieldNames;
    }

    public void setFieldNames(Set<String> fieldNames) {
        this.fieldNames = fieldNames;
    }

    public String getAllmans() {
        return allmans;
    }

    public void setAllmans(String allmans) {
        this.allmans = allmans;
    }

    public int getBackStepNo() {
        return backStepNo;
    }

    public void setBackStepNo(int backStepNo) {
        this.backStepNo = backStepNo;
    }
}

